
import config from "@/config";
// import { useUserStore } from "@/store/user";
import { weAtob, weBtoa } from "./weappJwt";
const ais = uni.getAccountInfoSync();
const env : string = ais.miniProgram.envVersion;

/**
 * 根据字符串获取长度
 * @param {any} str 
 * @return 
 */
export function getStringLength(str : string) {
	let length = 0;
	for (let i = 0; i < str.length; i++) {
		const charCode = str.charCodeAt(i);
		length += charCode >= 0 && charCode <= 128 ? 1 : 2;
	}
	return length;
}


/**
 * 匹配两个对象，把新对象nval中与默认对象比较，没有的字段要加上
 */
export const ObjectAssign = (nval : any = {}, oval : any = {}) => {
	// nval,oval
	// let oKeys=
	Object.keys(oval).map((okey) => {
		if (nval[okey]) {
			nval[okey] = oval[okey];
		} else {
			nval[okey] = oval[okey];
		}
	})
	return nval;
}

// 对象数据转换为地址参数
export const handleQuery = (obj : any = {}) => {
	if (Object.keys(obj).length === 0) return ''
	let str = '?'
	for (let key in obj) {
		str += `${key}=${obj[key]}` + '&'
	}
	return str.substr(0, str.length - 1)
}

// 获取图片baseUrl
export function getImgUrl() : string {
	return config['baseImgUrl'][env]
}

// 获取默认头像路径
export function getDefaultAvatar(){
	return config['defaultAvatar'];
}

// 获取默认头像路径
export function getDefaultCover(){
	return config['defaultCover'];
}

// 获取请求baseUrl
export function getBaseUrl() : string {
	return config['baseUrl'][env];
}

// 判空字符串
export function isEmptyStr(s : string) : boolean {
	if (!s || s.trim().length === 0) return true;
	return false;
}

// 对比两个对象的值是否完全相等 返回值 true/false
export function isObjectValueEqual(a : any, b : any) : boolean {
	//取对象a和b的属性名
	const aProps : string[] = Object.getOwnPropertyNames(a)
	const bProps : string[] = Object.getOwnPropertyNames(b)
	//判断属性名的length是否一致
	if (aProps.length != bProps.length) {
		return false
	}
	//循环取出属性名，再判断属性值是否一致
	for (let i = 0; i < aProps.length; i++) {
		const propName : string = aProps[i]
		if (a[propName] !== b[propName]) {
			return false
		}
	}
	return true
}


// // 上传文件
// export async function uploadFile(data : {
// 	url : string, filePath : string, name : string, fileType : 'image' | 'video' | 'audio'; params : any
// }) : Promise<{ data : any; statusCode : number }> {
// 	return new Promise((resolve, reject) => {
// 		const { url, filePath, name, fileType, params } = data;
// 		const userStore = useUserStore();
// 		uni.uploadFile({
// 			url,
// 			filePath,
// 			name,
// 			formData: params,
// 			fileType,
// 			header: {
// 				"Content-Type": "multipart/form-data",
// 				// 'X-Access-Token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODU1MDMxMTMsInVzZXJuYW1lIjoiYWRtaW4ifQ.br9oLg_eP7fiU-UhbFREJa2XHsb-irPPEOFfRVPbZdY'
// 				'X-Access-Token': userStore.token

// 			},
// 			success(uploadFileRes : any) : void {
// 				resolve(JSON.parse(uploadFileRes.data));
// 			},
// 			fail(err) {
// 				reject(err);
// 			}
// 		})
// 	})
// }


// 判断是否为base64格式
export function isBase64(str : String) : boolean {
	if (typeof str === 'string') {
		const image : string = str.trim().replace(/^data:image\/\w+;base64,/, "");
		try {
			weBtoa(weAtob(image));
			return true;
		} catch (err) {
			console.log('err', err);
			return false;
		}
	}
	return false;
}


/**
 * 十六进制值转rgba值
 * @method colorToRgb
 * @param sColor {string} '#00ff00'/'#00ff00ff'
 * @param returnType {int} 0: RGB(0,0,0)/rgba(0,0,0,0) || 1: [0,0,0] || 2:{rgba}
 * @param alpha {int} 优先认8位颜色的a值
 * @returns {*}
 */
export function colorToRgb(sColor : string, returnType : 0 | 1 | 2, alpha ?: number) {
	sColor = sColor.toLowerCase();
	var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/;
	if (sColor && reg.test(sColor)) {
		if (sColor.length === 4) {
			var sColorNew = "#";
			for (var i = 1; i < 4; i += 1) {
				sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
			}
			sColor = sColorNew;
		}
		//处理6-8位的颜色值
		var sColorChange = [];
		sColor = sColor.slice(1);
		for (var i = 0; i < sColor.length; i += 2) {
			sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
		}
		if (returnType == 0) {
			if (sColorChange.length == 4)
				sColorChange[3] /= 255;
			else if (typeof alpha != 'undefined')
				sColorChange.push(alpha)
			var prefix = sColorChange.length == 4 ? 'rgba(' : 'RGB(';
			return prefix + sColorChange.join(",") + ")";
		}
		else if (returnType == 1) {
			if (sColorChange.length < 4)
				sColorChange.push((typeof alpha != 'undefined' ? alpha : 1) * 255);
			return sColorChange;
		}
		else if (returnType == 2) {
			return { r: sColorChange[0], g: sColorChange[1], b: sColorChange[2], a: sColorChange[3] || (typeof alpha != 'undefined' ? alpha : 1) }
		}
	} else {
		return sColor;
	}
}

/**
 * 经纬度算公里
 * @param {number} lat1 
 * @param {number} lng1 
 * @param {number} lat2 
 * @param {number} lng2 
 * @return 
 */ 
export function getDistances(lat1 : number, lng1 : number, lat2 : number, lng2 : number) {
	let EARTH_RADIUS = 6378.137;// 地球半径
	let radLat1 = lat1 * Math.PI / 180.0; //lat1 * Math.PI / 180.0=>弧度计算
	let radLat2 = lat2 * Math.PI / 180.0;
	let a = radLat1 - radLat2;
	let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
	let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
	s = s * EARTH_RADIUS;
	s = Math.round(s * 10000) / 10000;// 输出为公里
	return { m: s * 1000, km: Number(s.toFixed(2)) }
}